<template>
    <div class="recommendDetail">
        <!-- 商品详情展示 -->
        <div class="container">
            <div class="img">
                <img :src="item.imageUrl" :alt="item.name" />
            </div>
            <div class="infoContainer">
                <h2 class="title">{{ item.name }}</h2>
                <p class="price">{{ item.price ? item.price + '日元' : '免费' }}</p>
                <p class="desc">{{ item.longDesc }}</p>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="actionButtons">
            <button class="btn addCart" @click="addToCart">加入购物车</button>
            <button class="btn buyNow" @click="showPurchasePanel">立即购买</button>
        </div>

        <!-- 购买面板 (底部弹出) -->
        <div class="purchasePanel" :class="{ active: showPanel }">
            <div class="panelHeader">
                <h3>购买详情</h3>
                <button class="closeBtn" @click="hidePurchasePanel">×</button>
            </div>

            <div class="panelContent">
                <!-- 日期选择 -->
                <div class="formGroup">
                    <label>选择日期：</label>
                    <div class="dateGrid">
                        <div v-for="day in availableDates" :key="day" class="dateCell"
                            :class="{ selected: selectedDate === day }" @click="selectDate(day)">
                            {{ formatDate(day) }}
                        </div>
                    </div>
                </div>

                <!-- 数量选择 -->
                <div class="formGroup">
                    <label>选择数量：</label>
                    <div class="quantitySelector">
                        <button class="qtyBtn" @click="decreaseQty">-</button>
                        <span class="qtyDisplay">{{ quantity }}</span>
                        <button class="qtyBtn" @click="increaseQty">+</button>
                    </div>
                </div>

                <!-- 总价计算 -->
                <div class="totalPrice">
                    总计：<span>{{ totalPrice }}日元</span>
                </div>
            </div>

            <button class="confirmBtn" @click="confirmPurchase">确认购买</button>
        </div>

        <!-- 遮罩层 -->
        <div class="overlay" v-if="showPanel" @click="hidePurchasePanel"></div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'

// 通过路由获取商品ID
const route = useRoute()
const itemId = route.params.id // 从路由参数获取ID

// 商品数据
const item = ref({
    id: '',
    name: '',
    price: 0,
    imageUrl: '',
    longDesc: ''
})

// 购买面板状态
const showPanel = ref(false)
const selectedDate = ref('')
const quantity = ref(1)

// 生成未来7天的可选日期
const availableDates = computed(() => {
    const dates = []
    const today = new Date()
    for (let i = 0; i < 7; i++) {
        const date = new Date()
        date.setDate(today.getDate() + i)
        dates.push(date.toISOString().split('T')[0])
    }
    return dates
})

// 格式化日期显示
const formatDate = (dateStr) => {
    const date = new Date(dateStr)
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${month}月${day}日`
}

// 计算总价
const totalPrice = computed(() => {
    return item.value.price * quantity.value
})

// 显示/隐藏购买面板
const showPurchasePanel = () => {
    showPanel.value = true
    // 默认选择第一个可用日期
    if (availableDates.value.length > 0 && !selectedDate.value) {
        selectedDate.value = availableDates.value[0]
    }
}

const hidePurchasePanel = () => {
    showPanel.value = false
}

// 日期选择
const selectDate = (date) => {
    selectedDate.value = date
}

// 数量增减
const increaseQty = () => {
    quantity.value += 1
}

const decreaseQty = () => {
    if (quantity.value > 1) {
        quantity.value -= 1
    }
}

// 加入购物车：addToCart
const addToCart = () => {
    const cartItem = {
        ...item.value,
        selectedDate: selectedDate.value,
        quantity: quantity.value,
        addedAt: new Date().toISOString()
    }

    // 获取现有购物车或初始化
    const cart = JSON.parse(localStorage.getItem('cart') || '[]')

    // 检查是否已存在相同商品
    const existingIndex = cart.findIndex(
        i => i.id === item.value.id && i.selectedDate === selectedDate.value
    )

    if (existingIndex >= 0) {
        // 更新数量
        cart[existingIndex].quantity += quantity.value
    } else {
        // 添加新商品
        cart.push(cartItem)
    }

    // 保存到localStorage
    localStorage.setItem('cart', JSON.stringify(cart))
    alert('已成功加入购物车')
    hidePurchasePanel()
}

// 确认购买
const confirmPurchase = () => {
    const order = {
        id: Date.now(),
        item: item.value,
        date: selectedDate.value,
        quantity: quantity.value,
        totalPrice: totalPrice.value,
        createdAt: new Date().toISOString(),
        status: 'pending'
    }

    // 获取现有订单或初始化
    const orders = JSON.parse(localStorage.getItem('orders') || '[]')
    orders.push(order)

    // 保存到localStorage
    localStorage.setItem('orders', JSON.stringify(orders))

    console.log('订单已保存:', order)

    alert('购买成功！订单号：' + order.id)
    hidePurchasePanel()
}

// 初始化时从API获取商品详情
onMounted(() => {
    fetchProductDetail()
})

// 获取商品详情
const fetchProductDetail = async () => {
    try {
        const response = await axios.get(`http://localhost:3000/TokyoSpots/${itemId}`)
        item.value = response.data
    } catch (error) {
        console.error('获取商品详情失败:', error)
    }
}
</script>

<style lang="css" scoped>
.recommendDetail {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    margin-bottom:100px;
}

.container {
    display: flex;
    gap: 40px;
    margin-bottom: 30px;
}

.img {
    flex: 1;
    max-width: 600px;
}

.spotImage {
    width: 100%;
    border-radius: 12px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.infoContainer {
    flex: 1;
}

.title {
    font-size: 28px;
    color: #333;
    margin-bottom: 15px;
}

.price {
    font-size: 24px;
    color: #ff6b81;
    font-weight: bold;
    margin-bottom: 20px;
}

.desc {
    font-size: 16px;
    line-height: 1.6;
    color: #666;
}

.actionButtons {
    display: flex;
    gap: 20px;
    margin-top: 40px;
}

.btn {
    padding: 12px 30px;
    border: none;
    border-radius: 50px;
    font-size: 16px;
    font-weight: bold;
    cursor: pointer;
    transition: all 0.3s ease;
}

.addCart {
    background-color: #fff;
    color: #ff6b81;
    border: 2px solid #ff6b81;
}

.addCart:hover {
    background-color: #ff6b81;
    color: white;
}

.buyNow {
    background-color: #ff6b81;
    color: white;
}

.buyNow:hover {
    background-color: #ff4757;
    transform: translateY(-2px);
}

/* 购买面板样式 */
.purchasePanel {
    position: fixed;
    bottom: -100%;
    left: 0;
    right: 0;
    background: white;
    border-radius: 20px 20px 0 0;
    padding: 25px;
    box-shadow: 0 -5px 20px rgba(0, 0, 0, 0.1);
    z-index: 100;
    transition: bottom 0.3s ease;
    margin-bottom: 50px;
}

.purchasePanel.active {
    bottom: 0;
}

.panelHeader {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
}

.closeBtn {
    font-size: 24px;
    background: none;
    border: none;
    cursor: pointer;
    color: #999;
}

/* 日期选择网格 */
.dateGrid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 10px;
    margin-top: 10px;
}

.dateCell {
    padding: 10px;
    text-align: center;
    border: 1px solid #ddd;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s;
}

.dateCell:hover {
    border-color: #ff6b81;
}

.dateCell.selected {
    background-color: #ff6b81;
    color: white;
    border-color: #ff6b81;
}

/* 数量选择器 */
.quantitySelector {
    display: flex;
    align-items: center;
    margin-top: 10px;
}

.qtyBtn {
    width: 40px;
    height: 40px;
    font-size: 20px;
    background: #f5f5f5;
    border: none;
    border-radius: 8px;
    cursor: pointer;
}

.qtyDisplay {
    margin: 0 15px;
    font-size: 18px;
    min-width: 30px;
    text-align: center;
}

/* 总价显示 */
.totalPrice {
    margin-top: 20px;
    font-size: 18px;
    text-align: right;
}

.totalPrice span {
    font-size: 22px;
    color: #ff6b81;
    font-weight: bold;
}

.confirmBtn {
    width: 100%;
    padding: 15px;
    margin-top: 20px;
    background: #ff6b81;
    color: white;
    font-size: 18px;
    border: none;
    border-radius: 50px;
    cursor: pointer;
}

/* 遮罩层 */
.overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 99;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .container {
        flex-direction: column;
    }

    .dateGrid {
        grid-template-columns: repeat(3, 1fr);
    }
}

@media (max-width: 480px) {
    .dateGrid {
        grid-template-columns: repeat(2, 1fr);
    }

    .actionButtons {
        flex-direction: column;
    }
}
</style>